import { UserRole } from './prisma-types';

export type ResourcePermission = 
  | '*'                  // 所有权限
  | 'read:*'            // 读取所有
  | 'write:own'         // 写入自己的
  | 'manage:students'   // 管理学生
  | 'read:own'          // 读取自己的
  | 'create:question'   // 创建问题
  | 'edit:question'     // 编辑问题
  | 'delete:question'   // 删除问题
  | 'submit:answer'     // 提交答案
  | 'grade:submission'  // 评分提交
  | 'view:analytics'    // 查看分析
  | 'manage:users';     // 管理用户

export type PermissionAction = 'create' | 'read' | 'update' | 'delete' | 'manage';
export type ResourceType = 'question' | 'submission' | 'evaluation' | 'user' | 'analytics';

export interface Permission {
  action: PermissionAction;
  resource: ResourceType;
  scope?: 'own' | 'all';
}

export const ROLE_PERMISSIONS: Record<UserRole, ResourcePermission[]> = {
  [UserRole.ADMIN]: ['*'],
  [UserRole.TEACHER]: [
    'read:*',
    'write:own',
    'manage:students',
    'create:question',
    'edit:question',
    'delete:question',
    'grade:submission',
    'view:analytics'
  ],
  [UserRole.STUDENT]: [
    'read:own',
    'write:own',
    'submit:answer'
  ]
};

export const RESOURCE_PERMISSIONS: Record<ResourceType, PermissionAction[]> = {
  question: ['create', 'read', 'update', 'delete'],
  submission: ['create', 'read', 'update'],
  evaluation: ['create', 'read', 'update'],
  user: ['create', 'read', 'update', 'delete', 'manage'],
  analytics: ['read']
};

export function hasPermission(userRole: UserRole, required: ResourcePermission): boolean {
  const permissions = ROLE_PERMISSIONS[userRole];
  return permissions.includes('*') || permissions.includes(required);
}

export function checkPermission(
  userRole: UserRole, 
  action: PermissionAction, 
  resource: ResourceType, 
  scope: 'own' | 'all' = 'own'
): boolean {
  const permissions = ROLE_PERMISSIONS[userRole];
  
  // Admin has all permissions
  if (permissions.includes('*')) {
    return true;
  }

  // Check specific permission combinations
  const specificPermission = `${action}:${resource}` as ResourcePermission;
  if (permissions.includes(specificPermission)) {
    return true;
  }

  // Check scoped permissions
  if (scope === 'own' && permissions.includes('write:own')) {
    return true;
  }

  if (permissions.includes('read:*')) {
    return action === 'read';
  }

  return false;
}

export function getRolePermissions(role: UserRole): ResourcePermission[] {
  return ROLE_PERMISSIONS[role];
}

export function validateResourceAccess(
  userRole: UserRole,
  action: PermissionAction,
  resource: ResourceType,
  isOwner: boolean
): boolean {
  const scope = isOwner ? 'own' : 'all';
  return checkPermission(userRole, action, resource, scope);
}
